package com.lhj.es.util;

import com.tencent.wework.Finance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 图片是jpg、视频是MP4、语音是amr
 * @author linghaijin
 * @date 2021-09-26 14:34
 */
public class DownMediaData {

    private final static Logger logger = LoggerFactory.getLogger(WeSessionBackUpUtil.class);
    private static long sdk = 0;
    private static long timeout = 10 * 60 * 1000;

    public static void initSDK() {
        if (sdk == 0) {
            sdk = Finance.NewSdk();
            Finance.Init(sdk, "ww3a4b6f1af19c38ce", "QqkpWR4VtqVmWyz9JLoyLZJ5lJcJxygq7rLFNyYE09o");
        }
    }


    public static void main(String[] args) throws FileNotFoundException {
        String sdkfileid = "CtsDKjEqSHRKUjBGaDR1ZWpMT3NGZTJDTUlnOTdJSVZWUzh3K1U0bUtBV2JRRENMVjh1SDFtQnJuUzZCbTFmT3V1eTMybWdodkxRT0IwWFYvM0tvK1dXQ1ppT0FSaUI3ZlM3Q2hjb0hiUklOMUk0eDRXalN5WUo3ZzZXaEZobytOYXlDY2MzUy9NYi9Od25aZjc3MHFrKzdQY1NSbnJSdFJvYmN2NFd6UjNqdU5lc1hKMjduZk1maWlHN2RMVWU2WktvY0NkdC9UZnlJOEJNTHhSQTlZYmF1OVUxRjMrcnhCNVA2anRLOXVOWVNlbHFvUHVDaG1hWC9rQ0lTUG9iNGZaSzZWdUk2OXZGOXNpeUpmRkg1S0ZMY0ZWYW1OUkw0NEZXN2FWbUxpWmtXamJCNVZYTEtZWkh6RGt4dG16UHMxQkFpZ0FCL2Q3MGRFbVI1M011L01zMHUrVmptZGlTeUtXcUpKQ0JTZDZTSExyeFVmVFJxYXdjZlV4SnprZUVBa0JRVzlNa0FPZUFUNzAyVlRuUDVkRTRpMlp6eloxZXh1Z2owQmFoeVl5SmJkSE5OTHpxaGZRYTdkVnI3L1F6ZTZ3NFBudEE0cHdXbkFuYXhxUDFuL3pCNm1HelE9PRI4TkRkZk1UWTRPRGcwT1RrM05ESTBOemN3Tmw4NU5EYzFOelEyTkRSZk1UWXpNalkwTWpNek13PT0aIDY1NmI3OTZmNzI2ZjczNjg3OTZkNmM3NTZmNjM2OTY1";
        String savefile = "C:\\Users\\linghaijin\\work\\测试语音.amr";
        initSDK();
//        FileOutputStream outputStream = new FileOutputStream(new File(savefile), true);
//        downloadMedia(outputStream, "", sdkfileid);

        String indexbuf = "";
        long ret = 0;
        while (true) {
            //每次使用GetMediaData拉取存档前需要调用NewMediaData获取一个media_data，在使用完media_data中数据后，还需要调用FreeMediaData释放。
            long media_data = Finance.NewMediaData();
            ret = Finance.GetMediaData(sdk, indexbuf, sdkfileid, "", "", timeout, media_data);
            if (ret != 0) {
                System.out.println("getmediadata ret:" + ret);
                Finance.FreeMediaData(media_data);
                return;
            }
            System.out.printf("getmediadata outindex len:%d, data_len:%d, is_finis:%d\n", Finance.GetIndexLen(media_data), Finance.GetDataLen(media_data), Finance.IsMediaDataFinish(media_data));
            try {
                //大于512k的文件会分片拉取，此处需要使用追加写，避免后面的分片覆盖之前的数据。
                FileOutputStream outputStream = new FileOutputStream(new File(savefile), true);
                outputStream.write(Finance.GetData(media_data));
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (Finance.IsMediaDataFinish(media_data) == 1) {
                //已经拉取完成最后一个分片
                Finance.FreeMediaData(media_data);
                break;
            } else {
                //获取下次拉取需要使用的indexbuf
                indexbuf = Finance.GetOutIndexBuf(media_data);
                Finance.FreeMediaData(media_data);
            }
        }
    }


    public static void downloadMedia(FileOutputStream outputStream, String indexBuf, String sdkFileId) {
        long mediaData = Finance.NewMediaData();
        long ret = Finance.GetMediaData(sdk, indexBuf, sdkFileId, "", "", timeout, mediaData);
        if (ret != 0) {
            logger.warn("获取媒体数据 " + ret);
        } else {
            logger.debug("upload media  " + sdkFileId);
            try {
                outputStream.write(Finance.GetData(mediaData));
                outputStream.flush();
            } catch (IOException e) {
                logger.error("写入媒体数据异常：", e);
            }
            boolean isFinish = Finance.IsMediaDataFinish(mediaData) > 0;
            String outIndex = Finance.GetOutIndexBuf(mediaData);
            if (isFinish) {
                logger.debug("upload media finish " + sdkFileId);
                try {
                    outputStream.close();
                } catch (IOException e) {
                    logger.error("写入媒体数据异常：", e);
                }
            } else {
                downloadMedia(outputStream, outIndex, sdkFileId);
            }
        }
    }
}
